<?php
namespace app\index\controller;

use think\Controller;
use app\service\MqttMessageHandler;
use think\Db;
use think\facade\Log;

/**
 * MQTT消息处理测试控制器
 */
class MqttTest extends Controller
{
    /**
     * 测试MQTT消息解析
     */
    public function testMessageParsing()
    {

        $logData = [
            'imei' => '12121',
            'iccid' => '123213',
            'content' => '',
            'createtime' => date('Y-m-d H:i:s')
        ];

        $result = Db::connect('db_config2')->name('log')->insert($logData);
        var_dump($result);exit;

        // 模拟您提供的MQTT消息数据
        $testTopic = 'tc/device/out/1C3426522542';
        $testMessage = [
            "api_version" => "1.0",
            "upload_data_type" => "normal",
            "cur_sim_id" => 2,
            "cur_sim_cato" => 0,
            "sim_info" => [
                [
                    "sim_id" => 2,
                    "sim_exist" => 1,
                    "sim_imsi" => "460080874008999",
                    "sim_iccid" => "898604881924d1098999",
                    "sim_mcc" => "460",
                    "sim_mnc" => "00",
                    "sim_lac" => 0,
                    "sim_tac" => 1448049,
                    "sim_snr" => 0,
                    "sim_dbm" => -85,
                    "sim_cell_id" => 514,
                    "sim_earfcn" => 504990,
                    "celltype" => 5,
                    "netmode" => 0,
                    "sim_network_status" => 1,
                    "sim_signal_level" => 4,
                    "sim_band" => 41,
                    "sim_operator" => "CMCC"
                ],
                [
                    "sim_id" => 1,
                    "sim_exist" => 0
                ]
            ],
            "system_info" => [
                "sys_running_time" => "00:41:08",
                "sys_current_time" => "2025-09-08 12:08:50",
                "sys_charge_status" => 1,
                "sys_bat_level" => 67,
                "sys_board_temperature" => 41,
                "sys_device_status" => 0,
                "fota_status" => 1
            ],
            "hotspot_info" => [
                "hotspot_connected_num" => 0,
                "hotspot_whether_hide" => 0,
                "hotspot_whether_on" => 1,
                "hotspot_name" => "MIFI-000007-2.4G",
                "hotspot_password" => "12345678",
                "hotspot_channel" => 0,
                "hotspot_connected_num_max" => 32,
                "hotspot_encryption_mode" => 2,
                "hotspot_gateway_ip" => "",
                "hotspot_start_ip" => "",
                "hotspot_end_ip" => "",
                "hotspot_whether_5g" => 0,
                "hotspot_black_clients" => "[]",
                "hotspot_connected_clients" => [],
                "hotspot_wps_status" => 0
            ],
            "hotspot_info_5g" => [
                "hotspot_connected_num" => 0,
                "hotspot_whether_hide" => 0,
                "hotspot_whether_on" => 1,
                "hotspot_name" => "MIFI-000007-5G",
                "hotspot_password" => "12345678",
                "hotspot_channel" => 0,
                "hotspot_connected_num_max" => 32,
                "hotspot_encryption_mode" => 2,
                "hotspot_gateway_ip" => "",
                "hotspot_start_ip" => "",
                "hotspot_end_ip" => "",
                "hotspot_whether_5g" => 1,
                "hotspot_black_clients" => "[]",
                "hotspot_connected_clients" => [],
                "hotspot_wps_status" => 0
            ],
            "network_info" => [
                "network_ip_addr" => "10.93.44.95",
                "network_strength_status" => -86,
                "network_upload_dataflow" => "3KB",
                "network_download_dataflow" => "0KB",
                "network_upload_speed_limit" => "0KB",
                "network_download_speed_limit" => "0KB",
                "network_daily_upload_dataflow" => "0",
                "network_daily_download_dataflow" => "0"
            ],
            "device_info" => [
                "dev_imei1" => "863780074784151",
                "dev_imei2" => "863780074784169",
                "dev_sn" => "506112000007",
                "dev_mac" => "1c:34:26:52:25:42",
                "dev_sw_version" => "V1.0",
                "dev_hw_version" => "L70MB",
                "dev_project_name" => "udx710_l70mb-ty58-l77_tybg_h3_dks_sign4_1.54p_p6_256mb_5g_nr_user_20250820165052",
                "dev_reset_flag" => 1,
                "m_type" => 0,
                "realname_sim" => "1,0,1",
                "sim_id" => 2,
                "is_force_enable" => 0
            ],
            "switch_sim_info" => [
                "switch_array" => "0123",
                "switch_mode" => 0,
                "current_sim_id" => 2
            ]
        ];

        try {
            // 创建消息处理器实例
            $handler = new MqttMessageHandler();

            // 处理消息
            $result = $handler->handle($testTopic, $testMessage);

            // 强制保存到数据库
            $handler->flush();

            return json([
                'code' => 1,
                'msg' => '测试消息处理完成',
                'data' => [
                    'topic' => $testTopic,
                    'result' => $result,
                    'timestamp' => date('Y-m-d H:i:s')
                ]
            ]);

        } catch (\Throwable $e) {
            Log::error('测试MQTT消息处理失败: ' . $e->getMessage());
            return json([
                'code' => 0,
                'msg' => '测试失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 查看flow_wifi_imei表中的数据 (默认数据库)
     */
    public function viewData()
    {
        try {
            $data = \think\Db::name('flow_wifi_imei')
                ->order('wifi_imei_id desc')
                ->limit(10)
                ->select();

            return json([
                'code' => 1,
                'msg' => '查询成功 (默认数据库)',
                'data' => $data
            ]);
        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'msg' => '查询失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 测试使用第二个数据库保存MQTT消息
     */
    public function testSecondDb()
    {
        // 模拟MQTT消息数据 (简化版)
        $testTopic = 'tc/device/out/1C3426522542';
        $testMessage = [
            "device_info" => [
                "dev_imei1" => "863780074784999", // 使用不同的IMEI避免冲突
            ],
            "sim_info" => [
                [
                    "sim_id" => 2,
                    "sim_exist" => 1,
                    "sim_iccid" => "898604881924d1099999",
                    "sim_mnc" => "00",
                    "sim_dbm" => -88,
                    "sim_signal_level" => 3,
                ]
            ],
            "cur_sim_id" => 2,
            "system_info" => [
                "sys_bat_level" => 75,
            ],
            "hotspot_info_5g" => [
                "hotspot_name" => "MIFI-TEST-5G",
                "hotspot_password" => "87654321",
                "hotspot_whether_hide" => 0,
                "hotspot_connected_num" => 1,
                "hotspot_whether_5g" => 1,
            ]
        ];

        try {
            // 创建消息处理器实例并设置使用第二个数据库
            $handler = new MqttMessageHandler();
            $handler->setDbConnection('db_config2'); // 使用第二个数据库

            // 处理消息
            $result = $handler->handle($testTopic, $testMessage);

            // 强制保存到数据库
            $handler->flush();

            return json([
                'code' => 1,
                'msg' => '第二个数据库测试完成',
                'data' => [
                    'topic' => $testTopic,
                    'result' => $result,
                    'database' => 'db_config2',
                    'timestamp' => date('Y-m-d H:i:s')
                ]
            ]);

        } catch (\Throwable $e) {
            Log::error('第二个数据库测试失败: ' . $e->getMessage());
            return json([
                'code' => 0,
                'msg' => '第二个数据库测试失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 测试新的更新流程 - 只更新已存在的记录
     */
    public function testUpdateOnly()
    {
        // 测试两个IMEI：一个存在，一个不存在
        $testMessages = [
            // 第一个消息 - 使用可能存在的IMEI
            [
                'topic' => 'tc/device/out/1C3426522542',
                'data' => [
                    "device_info" => [
                        "dev_imei1" => "863780074784151", // 使用之前测试的IMEI
                    ],
                    "sim_info" => [
                        [
                            "sim_id" => 2,
                            "sim_exist" => 1,
                            "sim_iccid" => "898604881924d1098999",
                            "sim_mnc" => "00",
                            "sim_dbm" => -90,
                            "sim_signal_level" => 2,
                        ]
                    ],
                    "cur_sim_id" => 2,
                    "system_info" => [
                        "sys_bat_level" => 85,
                    ],
                    "hotspot_info_5g" => [
                        "hotspot_name" => "MIFI-UPDATE-TEST",
                        "hotspot_password" => "newpassword123",
                        "hotspot_whether_hide" => 1,
                        "hotspot_connected_num" => 2,
                        "hotspot_whether_5g" => 1,
                    ]
                ]
            ],
            // 第二个消息 - 使用不存在的IMEI
            [
                'topic' => 'tc/device/out/1C3426522542',
                'data' => [
                    "device_info" => [
                        "dev_imei1" => "999999999999999", // 不存在的IMEI
                    ],
                    "sim_info" => [
                        [
                            "sim_id" => 1,
                            "sim_exist" => 1,
                            "sim_iccid" => "999999999999999999",
                            "sim_mnc" => "01",
                            "sim_dbm" => -75,
                            "sim_signal_level" => 4,
                        ]
                    ],
                    "cur_sim_id" => 1,
                    "system_info" => [
                        "sys_bat_level" => 50,
                    ],
                    "hotspot_info_5g" => [
                        "hotspot_name" => "SHOULD-NOT-SAVE",
                        "hotspot_password" => "shouldnotsave",
                        "hotspot_whether_hide" => 0,
                        "hotspot_connected_num" => 0,
                        "hotspot_whether_5g" => 1,
                    ]
                ]
            ]
        ];

        try {
            $handler = new MqttMessageHandler();
            $results = [];

            foreach ($testMessages as $index => $message) {
                $result = $handler->handle($message['topic'], $message['data']);
                $results[] = [
                    'message_index' => $index + 1,
                    'imei' => $message['data']['device_info']['dev_imei1'],
                    'result' => $result
                ];
            }

            // 强制保存到数据库
            $handler->flush();

            return json([
                'code' => 1,
                'msg' => '更新流程测试完成',
                'data' => [
                    'test_results' => $results,
                    'description' => '第一个IMEI应该更新成功，第二个IMEI应该被跳过',
                    'timestamp' => date('Y-m-d H:i:s')
                ]
            ]);

        } catch (\Throwable $e) {
            Log::error('更新流程测试失败: ' . $e->getMessage());
            return json([
                'code' => 0,
                'msg' => '更新流程测试失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 测试缓存优化效果
     */
    public function testCacheOptimization()
    {
        $testImei = "863780074784151";
        $results = [];

        try {
            $handler = new MqttMessageHandler();

            // 清除缓存，确保测试准确性
            $handler->clearImeiCache($testImei);

            // 第一次查询（应该查询数据库）
            $start1 = microtime(true);
            $exists1 = $handler->checkImeiExists($testImei);
            $end1 = microtime(true);
            $time1 = ($end1 - $start1) * 1000; // 转换为毫秒

            $results['first_query'] = [
                'exists' => $exists1,
                'time_ms' => round($time1, 2),
                'source' => 'database'
            ];

            // 第二次查询（应该从缓存获取）
            $start2 = microtime(true);
            $exists2 = $handler->checkImeiExists($testImei);
            $end2 = microtime(true);
            $time2 = ($end2 - $start2) * 1000;

            $results['second_query'] = [
                'exists' => $exists2,
                'time_ms' => round($time2, 2),
                'source' => 'cache'
            ];

            // 性能提升计算
            $improvement = 0;
            if ($time1 > 0) {
                $diff = $time1 - $time2;
                $improvement = round(($diff / $time1) * 100, 1);
            }

            $improvementText = $improvement . '%';

            return json([
                'code' => 1,
                'msg' => '缓存优化测试完成',
                'data' => [
                    'test_imei' => $testImei,
                    'results' => $results,
                    'performance_improvement' => $improvementText,
                    'cache_hit_faster' => $time2 < $time1,
                    'timestamp' => date('Y-m-d H:i:s')
                ]
            ]);

        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'msg' => '缓存测试失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 测试批量处理优化
     */
    public function testBatchOptimization()
    {
        try {
            $handler = new MqttMessageHandler();

            // 模拟多条MQTT消息
            $testMessages = [];
            $baseImei = "863780074784";

            // 生成10条测试消息
            for ($i = 1; $i <= 10; $i++) {
                $imei = $baseImei . str_pad($i, 3, '0', STR_PAD_LEFT);
                $testMessages[] = [
                    "device_info" => [
                        "dev_imei1" => $imei,
                    ],
                    "sim_info" => [
                        [
                            "sim_id" => 2,
                            "sim_exist" => 1,
                            "sim_iccid" => "898604881924d109" . str_pad($i, 4, '0', STR_PAD_LEFT),
                            "sim_mnc" => "00",
                            "sim_dbm" => -80 - $i,
                            "sim_signal_level" => 4,
                        ]
                    ],
                    "cur_sim_id" => 2,
                    "system_info" => [
                        "sys_bat_level" => 50 + $i * 3,
                    ],
                    "hotspot_info_5g" => [
                        "hotspot_name" => "MIFI-BATCH-{$i}",
                        "hotspot_password" => "batch{$i}123",
                        "hotspot_whether_hide" => $i % 2,
                        "hotspot_connected_num" => $i,
                        "hotspot_whether_5g" => 1,
                    ]
                ];
            }

            // 测试批量处理性能
            $start = microtime(true);

            foreach ($testMessages as $message) {
                $handler->handle('tc/device/out/test', $message);
            }

            // 强制保存（触发批量处理）
            $handler->flush();

            $end = microtime(true);
            $totalTime = ($end - $start) * 1000; // 转换为毫秒

            return json([
                'code' => 1,
                'msg' => '批量处理测试完成',
                'data' => [
                    'message_count' => count($testMessages),
                    'total_time_ms' => round($totalTime, 2),
                    'avg_time_per_message_ms' => round($totalTime / count($testMessages), 2),
                    'batch_size' => 100,
                    'description' => '测试了' . count($testMessages) . '条消息的批量处理性能',
                    'timestamp' => date('Y-m-d H:i:s')
                ]
            ]);

        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'msg' => '批量处理测试失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 测试数据库连接优化
     */
    public function testConnectionOptimization()
    {
        try {
            $handler = new MqttMessageHandler();
            $results = [];

            // 测试1: 连接复用测试
            $start1 = microtime(true);
            for ($i = 0; $i < 5; $i++) {
                $handler->checkImeiExists("863780074784151");
            }
            $end1 = microtime(true);
            $time1 = ($end1 - $start1) * 1000;

            $results['connection_reuse_test'] = [
                'operations' => 5,
                'total_time_ms' => round($time1, 2),
                'avg_time_per_op_ms' => round($time1 / 5, 2),
                'description' => '连接复用测试 - 5次查询操作'
            ];

            // 测试2: 批量操作测试
            $testImeis = [
                "863780074784151",
                "863780074784152",
                "863780074784153"
            ];

            $start2 = microtime(true);
            $existingImeis = $handler->batchCheckImeiExists($testImeis);
            $end2 = microtime(true);
            $time2 = ($end2 - $start2) * 1000;

            $results['batch_operation_test'] = [
                'imei_count' => count($testImeis),
                'found_count' => count($existingImeis),
                'total_time_ms' => round($time2, 2),
                'avg_time_per_imei_ms' => round($time2 / count($testImeis), 2),
                'description' => '批量查询测试'
            ];

            // 测试3: 错误恢复测试（模拟）
            $results['error_recovery_test'] = [
                'max_retries' => 3,
                'retry_delays' => ['100ms', '200ms', '300ms'],
                'connection_errors_handled' => [
                    'server has gone away',
                    'lost connection',
                    'connection timeout'
                ],
                'description' => '自动重连机制配置'
            ];

            return json([
                'code' => 1,
                'msg' => '数据库连接优化测试完成',
                'data' => [
                    'optimization_features' => [
                        '连接实例复用',
                        '智能重连机制',
                        '错误类型识别',
                        '递增延迟重试',
                        '移除不必要连接测试'
                    ],
                    'test_results' => $results,
                    'performance_benefits' => [
                        '减少连接开销',
                        '提高容错能力',
                        '降低网络延迟影响',
                        '提升系统稳定性'
                    ],
                    'timestamp' => date('Y-m-d H:i:s')
                ]
            ]);

        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'msg' => '连接优化测试失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 直接查询数据库验证IMEI是否存在
     */
    public function checkImeiInDatabase()
    {
        $testImei = "863780074784151";

        try {
            // 直接查询数据库
            $record = \think\Db::name('flow_wifi_imei')
                ->where('IMEI', $testImei)
                ->find();

            // 查询所有记录（用于调试）
            $allRecords = \think\Db::name('flow_wifi_imei')
                ->field('wifi_imei_id,IMEI,iccid,add_time')
                ->order('wifi_imei_id desc')
                ->limit(5)
                ->select();

            // 清除缓存
            $handler = new MqttMessageHandler();
            $handler->clearImeiCache($testImei);

            // 重新测试缓存查询
            $cacheResult = $handler->checkImeiExists($testImei);

            return json([
                'code' => 1,
                'msg' => '数据库查询验证完成',
                'data' => [
                    'test_imei' => $testImei,
                    'direct_query_result' => $record ? '存在' : '不存在',
                    'direct_query_data' => $record,
                    'cache_cleared' => true,
                    'cache_query_result' => $cacheResult ? '存在' : '不存在',
                    'recent_records' => $allRecords,
                    'table_name' => 'flow_wifi_imei',
                    'query_field' => 'IMEI',
                    'timestamp' => date('Y-m-d H:i:s')
                ]
            ]);

        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'msg' => '数据库查询失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 调试数据库查询差异
     */
    public function debugDbQuery()
    {
        $testImei = "863780074784151";

        try {
            // 方法1: 直接查询（测试控制器方式）
            $direct = \think\Db::name('flow_wifi_imei')
                ->where('IMEI', $testImei)
                ->find();

            // 方法2: 使用Db类查询
            $dbClass = \think\Db::name('flow_wifi_imei')
                ->where('IMEI', $testImei)
                ->find();

            // 方法3: 模拟MqttMessageHandler的查询方式
            $handler = new MqttMessageHandler();

            // 直接调用数据库，不通过executeDbOperation
            $handlerDirect = \think\Db::name('flow_wifi_imei')
                ->where('IMEI', $testImei)
                ->find();

            // 方法4: 通过handler的方法查询
            $handlerMethod = $handler->checkImeiExists($testImei);

            // 方法5: 检查缓存
            $cacheKey = 'imei_exists:' . $testImei;
            $cached = \think\facade\Cache::get($cacheKey);

            return json([
                'code' => 1,
                'msg' => '数据库查询对比完成',
                'data' => [
                    'test_imei' => $testImei,
                    'method1_direct_think_db' => [
                        'result' => $direct ? '存在' : '不存在',
                        'data' => $direct
                    ],
                    'method2_db_class' => [
                        'result' => $dbClass ? '存在' : '不存在',
                        'data' => $dbClass
                    ],
                    'method3_handler_direct' => [
                        'result' => $handlerDirect ? '存在' : '不存在',
                        'data' => $handlerDirect
                    ],
                    'method4_handler_method' => [
                        'result' => $handlerMethod ? '存在' : '不存在'
                    ],
                    'method5_cache_value' => [
                        'cached' => $cached,
                        'cache_key' => $cacheKey
                    ],
                    'timestamp' => date('Y-m-d H:i:s')
                ]
            ]);

        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'msg' => '调试查询失败: ' . $e->getMessage()
            ]);
        }
    }

    /**
     * 强制清除缓存并重新测试
     */
    public function forceClearCacheAndTest()
    {
        $testImei = "863780074784151";

        try {
            // 强制清除所有相关缓存
            $cacheKeys = [
                'imei_exists:' . $testImei,
                'imei_exists:863780074784151',
                'IMEI_EXISTS:' . $testImei,
                'IMEI_EXISTS:863780074784151'
            ];

            foreach ($cacheKeys as $key) {
                \think\facade\Cache::rm($key);
            }


            // 创建新的handler实例
            $handler = new MqttMessageHandler();

            // 直接调用数据库查询，完全绕过缓存
            $directQuery = \think\Db::name('flow_wifi_imei')
                ->where('IMEI', $testImei)
                ->find();

            // 模拟MQTT消息处理，但使用修改过的逻辑
            $testMessage = [
                "device_info" => ["dev_imei1" => $testImei],
                "sim_info" => [["sim_id" => 2, "sim_exist" => 1, "sim_iccid" => "test", "sim_mnc" => "00", "sim_dbm" => -85, "sim_signal_level" => 4]],
                "cur_sim_id" => 2,
                "system_info" => ["sys_bat_level" => 67],
                "hotspot_info_5g" => ["hotspot_name" => "TEST", "hotspot_password" => "test", "hotspot_whether_hide" => 0, "hotspot_connected_num" => 0, "hotspot_whether_5g" => 1]
            ];

            // 处理消息
            $result = $handler->handle('tc/device/out/test', $testMessage);

            // 强制保存
            //$handler->flush();

            return json([
                'code' => 1,
                'msg' => '强制清除缓存测试完成',
                'data' => [
                    'test_imei' => $testImei,
                    'cache_keys_cleared' => $cacheKeys,
                    'direct_db_query' => $directQuery ? '存在' : '不存在',
                    'direct_db_data' => $directQuery,
                    'mqtt_process_result' => $result,
                    'timestamp' => date('Y-m-d H:i:s')
                ]
            ]);

        } catch (\Throwable $e) {
            return json([
                'code' => 0,
                'msg' => '强制测试失败: ' . $e->getMessage()
            ]);
        }
    }


}
